#/user/bin/env python3
#!_*_ conding:utf-8 _*_
#!@Author:冰冰
#!@Time:2019-12-20 下午 6:37

import requests
import re,json,csv,pymysql

def index():
    base_url = "http://80.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112402987497847979377_1576835621013&pn=1&pz=2102&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:116+t:3&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152&_=1576835621014"
    response=requests.get(base_url)
    response.encoding=response.apparent_encoding
    html=response.text
    # print(html)
    txt=re.compile("(\[{.+?}\])")
    result=txt.findall(html)
    # print(result)
    list1=json.loads(result[0])
    for i in list1:
        try:
            a=i["f14"],i["f2"],i["f4"],i["f3"],i["f17"],i["f15"],i["f16"],i["f18"],i["f5"],i["f6"]
            print(a)
            # mysql_inster(a)
        except:
            print()
# def mysql_inster(a):
#     print(a)
#     db = pymysql.connect("192.168.0.164", "root", "123456", "wk", charset="utf8")
#     cursor=db.cursor()
#     sql="insert into jinrong value(0,'{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9])
#     print(sql)
#     cursor.execute(sql)
#     db.commit()
# index()


    with open(r"D:\jinrong.csv", "w+", encoding="utf-8_sig", newline="") as f:
        w = csv.writer(f)
        cname = ["序号","名称","最新价(HKD)", "涨跌额", "涨跌幅(%)","今开","最高","最低","昨收","成交量(股)","成交额(港元)"]
        w = csv.DictWriter(f, cname)
        w.writeheader()
        j = 1
        for i in list1:
            w.writerow(
                {
                    "序号":j,
                    "名称":i["f14"],
                    "最新价(HKD)": i["f2"],
                    "涨跌额": i["f4"],
                    "涨跌幅(%)": i["f3"],
                    "今开": i["f17"],
                    "最高": i["f15"],
                    "最低": i["f16"],
                    "昨收": i["f18"],
                    "成交量(股)": i["f5"],
                    "成交额(港元)": i["f6"]
                }
            )
            j+=1
index()